from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.api.v1.endpoints import tasks, analytics
from app.db.init_db import init_db
from app.services.sync_service import schedule_sync_tasks
import asyncio
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
)
logger = logging.getLogger(__name__)

app = FastAPI(
    title=settings.PROJECT_NAME,
    openapi_url=f"{settings.API_V1_STR}/openapi.json"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该限制为特定域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(tasks.router, prefix=f"{settings.API_V1_STR}/tasks", tags=["tasks"])
app.include_router(analytics.router, prefix=f"{settings.API_V1_STR}/analytics", tags=["analytics"])

@app.get("/")
async def root():
    return {"message": "Welcome to Data Sources API"}

@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {
        "status": "ok",
        "version": "1.0.0",
        "services": {
            "postgres": "up",
            "clickhouse": "up",
            "citusdb": "up"
        }
    }

# 启动时的任务
@app.on_event("startup")
async def startup_event():
    """应用启动时初始化数据库并启动后台任务"""
    try:
        # 初始化数据库
        await init_db()
        logger.info("数据库初始化成功")
        
        # 启动数据同步任务
        asyncio.create_task(schedule_sync_tasks())
        logger.info("数据同步任务已启动")
    except Exception as e:
        logger.error(f"启动任务失败: {str(e)}")

# 关闭时的任务
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时清理资源"""
    logger.info("应用正在关闭，清理资源...") 